import { HttpException } from '@/core/HttpException'

import transporter from '@/server/mailer/transporter'

interface MailOptions {
  from?: string //发件人
  to: string //收件人
  subject: string //主题
  text: string //plain text body
  html: string //html body
}
/**
 * 发送邮件
 * @param { MailOptions } mailOptions
 * @returns
 */
export async function sendEmail({ from = '"温海龙" <2273106083@qq.com>', to, subject, text, html }: MailOptions) {
  return new Promise((resolve, reject) => {
    const mailOptions = {
      from,
      to,
      subject,
      text,
      html,
    }
    transporter
      .sendMail(mailOptions)
      .then((res: { response: string | string[] }) => {
        // {
        //   accepted: [ 'thiswhl@163.com' ],
        //   rejected: [],
        //   ehlo: [
        //     'PIPELINING',
        //     'SIZE 73400320',
        //     'AUTH LOGIN PLAIN XOAUTH XOAUTH2',
        //     'AUTH=LOGIN',
        //     'MAILCOMPRESS',
        //     '8BITMIME'
        //   ],
        //   envelopeTime: 215,
        //   messageTime: 351,
        //   messageSize: 1337,
        //   response: '250 OK: queued as.',
        //   envelope: { from: '2273106083@qq.com', to: [ 'thiswhl@163.com' ] },
        //   messageId: '<9ae73655-6c70-33f4-882b-17f4169ccd16@qq.com>'
        // }
        if (res.response.indexOf('250') > -1) {
          resolve(true)
        } else {
          reject()
        }
      })
      .catch((error) => {
        throw new HttpException({ msg: error.msg })
      })
  })
}
